<template>
	<div class="default-main">

		<el-tabs v-model="tabActiveName" type="card" @tab-remove="removeTab">
			<el-tab-pane :closable="false" :label="isAdmin() ? '产线列表' : '我的产线'" class="line-list-tab-pane" name="collection">
				<cus-form-title id="userProduction-form-title" icon="local-cus-ruleEngine" label="搜索">
					<template #after>
						<div style="margin-left: 20px">
							<el-button icon="el-icon-Search" size="small" type="primary" @click="handleSearch">
								搜索
							</el-button>
							<el-button icon="el-icon-Refresh" size="small" type="primary" @click="resetSearch">
								重置
							</el-button>
						</div>
					</template>
				</cus-form-title>
				<el-form id="userProduction-form" ref="itemSearchForm" :disabled="isVisitor()" :model="params" class="cus-form" label-width="auto">
					<el-row :gutter="20" justify="start">
						<el-col :span="8">
							<el-form-item label="产线名称">
								<el-input v-model="params.productionName_like" clearable placeholder="模糊查询"
								          @keyup.enter="handleSearch"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="产物">
								<el-select v-model="params.itemId_eq" clearable filterable @change="handleSearch">
									<el-option v-for="item in itemOptionList" :key="item.id" :label="item.itemName!" :value="item.id">
										<span style="float: left">{{ item.itemName }}</span>
										<span v-if="item.image" style="float: right">
												<el-image :src="getImage(item.image)" fit="contain" style="width: 30px; height: 30px"/>
											</span>
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col v-if="isAdmin()" :span="8">
							<el-form-item label="用户">
								<el-select v-model="params.userId_eq" clearable filterable @change="handleSearch">
									<el-option v-for="user in userOptionList" :key="user.id" :label="`${user.nickname}（${user.username}）`" :value="user.id"/>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>

				<cus-table-title id="userProduction-table-title" icon="local-cus-ruleEngine" label="我的产线"/>
				<el-table v-loading="tableLoading" :data="tableData" :max-height="tableMaxHeight" border class="cus-table" fit highlight-current-row>
					<el-table-column align="center" label="序号" width="60">
						<template v-slot="scope">
							{{ initTableIndex(pageRef, scope.$index) }}
						</template>
					</el-table-column>
					<el-table-column v-if="isAdmin()" align="center" label="用户" prop="userDisplayName" show-overflow-tooltip width="300"></el-table-column>
					<el-table-column align="center" label="产线名称（左键查看，右键编辑）" min-width="400">
						<template v-slot="scope">
							<el-link :underline="false" type="primary" @click="showLineDetail(scope.row)" @contextmenu.prevent="onContextmenu(scope.row, $event)">{{
									scope.row.productionName
								}}
							</el-link>
						</template>
					</el-table-column>
					<el-table-column align="center" label="主要产物" min-width="250">
						<template v-slot="scope">
							<div class="cus-center">
								<el-link :underline="false" type="primary" @click="showItemDetail(scope.row.itemId)">{{ scope.row.itemName }}</el-link>
								<el-image v-if="scope.row.itemImage" :src="getImage(scope.row.itemImage)" fit="contain"
								          style="width: 100px; height: 100px;cursor: pointer;margin-left: 10px" @click="showItemDetail(scope.row.itemId)"></el-image>
							</div>
						</template>
					</el-table-column>
					<el-table-column align="center" label="需求数量" width="200">
						<template v-slot="scope">
							{{ `${scope.row.quantityPerMinute} /min` }}
						</template>
					</el-table-column>
				</el-table>
				<cus-pagination id="userProduction-pagination" ref="pageRef" v-model="tableData" v-model:loading="tableLoading" :autoBuild="false" :pageSize="10"
				                :params="params" url="/game/g-user-production/readOnly/pageUserProduction"/>
			</el-tab-pane>

			<el-tab-pane v-for="(item, index) in productionLineDataList" :key="'productionLineDataList_' + index" :label="item.label" :name="item.name" class="line-detail-tab-pane" closable>
				<production-line-detail :production-line-data="item"/>
			</el-tab-pane>
		</el-tabs>

		<!-- 对话框（物品详情） -->
		<cus-item-dialog v-model:visible="dialogVisible.item" :item-id="itemIdDisplayed"/>

		<context-menu ref="contextmenuRef" :items="contextmenuItems" @contextmenuItemClick="onContextmenuItem"/>

	</div>
</template>

<script lang="ts" name="ProductionLineCollectionOld" setup>

import {h, onActivated, onMounted, reactive, ref} from 'vue'
import {getImage, initTableIndex, messageInfo, messageSuccess, messageWarning} from '@/utils/commonUtil'
import {useI18n} from 'vue-i18n'
import CusPagination from '@/components/cus-pagination.vue'
import CusTableTitle from '@/components/cus-table-title.vue'
import CusFormTitle from '@/components/cus-form-title.vue'
import {calcMaxHeightWithExtra} from '@/utils/layoutUtil'
import {debounce, type DebouncedFunc, remove} from 'lodash-es'
import {useEventListener} from '@vueuse/core'
import {onBeforeRouteLeave} from 'vue-router'
import {hasPermission, isAdmin, isVisitor} from '@/utils/authUtil'
import {useUserStore} from '@/stores/modules/user.store'
import {deleteUserProductionApi, getAllItemApi, getAllUserApi, getUserProductionByIdApi, modifyProductionNameApi} from '@/api/gameTool/productionLine.api'
import CusItemDialog from '@/components/cus-item-dialog.vue'
import {ElMessageBox} from 'element-plus'
import ContextMenu from '@/components/contextmenu/index.vue'
import type {ContextMenuItem, ContextmenuItemClickEmitArg} from '@/components/contextmenu/interface'
import ProductionLineDetail from '@/components/production-line-detail-old.vue'
import type {TabPaneName} from 'element-plus/es/components/tabs/src/tabs'
import {useNavTabsStore} from '@/stores/modules/navTabs.store'
import {useRouteParamsStore} from '@/stores/modules/routeParams.store'

const {t} = useI18n()
const userStore = useUserStore()
const navTabsStore = useNavTabsStore()
const routeParamsStore = useRouteParamsStore()

const pageRef = ref()
const contextmenuRef = ref()

const onContextmenu = (row: ProductionCollectionVo, el: MouseEvent) => {
	const {clientX, clientY} = el
	contextmenuRef.value.onShowContextmenu(row, {
		x: clientX,
		y: clientY
	})
}

const contextmenuItems = ref<ContextMenuItem[]>([
	{name: 'editName', label: '重命名', icon: 'el-icon-Edit', disabled: !hasPermission('g-user-production:modifyProductionName')},
	{name: 'delete', label: '删除', icon: 'el-icon-Delete', disabled: !hasPermission('g-user-production:deleteUserProduction')}
])

const onContextmenuItem = async (item: ContextmenuItemClickEmitArg<ProductionCollectionVo>) => {
	const {name} = item
	const row = item.data
	if (!row) {
		return
	}
	switch (name) {
		case 'editName':
			ElMessageBox.prompt('新名称：', '重命名', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				draggable: true,
				inputValue: row.productionName
			}).then(({value}) => {
				if (value === row.productionName) {
					messageInfo('名称未变更')
					return
				}
				const request: ModifyProductionNameRequest = {
					userId: row.userId,
					productionId: row.id,
					productionName: value
				}
				doModifyProductionName(request, row.productionName)
			}).catch(() => {
			})
			break
		case 'delete':
			ElMessageBox({
				title: '删除收藏？',
				message: isAdmin() ? h('div', null, [
					h('p', null, `产线名称：${row.productionName}`),
					h('p', null, `用户：${row.userDisplayName}`)
				]) : h('div', null, `${row.productionName}`),
				showCancelButton: true,
				showConfirmButton: true,
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				draggable: true
			}).then(() => {
				deleteUserProductionApi(row.id).then(() => {
					messageSuccess(`已删除收藏：${row.productionName}`)
					pageRef.value!.buildData()
					// 方案1：使用el-tabs展示产线详情时，关闭已打开的产线详情tab
					removeTab(`ProductionLineDetail_${row.id}`)
					// 方案2：使用新标签页（动态路由）展示产线详情时，关闭已打开的产线详情标签页
					// for (const menuVo of navTabsStore.openedTabs) {
					// 	if (menuVo.name === `ProductionLineDetail_${row.id}`) {
					// 		navTabsStore.closeTab(menuVo)
					// 		break
					// 	}
					// }
				})
			}).catch(() => {
			})
			break
	}
}

const doModifyProductionName = (request: ModifyProductionNameRequest, originalName: string) => {
	modifyProductionNameApi(request).then(response => {
		if (response.data) {
			ElMessageBox.prompt('产线名称已存在，请更换其他名称：', '名称重复', {
				type: 'error',
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				draggable: true,
				inputValue: request.productionName
			}).then(({value}) => {
				if (value === originalName) {
					messageInfo('名称未变更')
					return
				}
				request.productionName = value
				doModifyProductionName(request, originalName)
			}).catch(() => {
			})
		} else {
			messageSuccess(t('successMessage.update'))
			pageRef.value!.buildData()
			// 方案1：使用el-tabs展示产线详情时，修改对应产线详情tab的label
			for (const item of productionLineDataList.value) {
				if (item.name === `ProductionLineDetail_${request.productionId}`) {
					item.label = request.productionName
					break
				}
			}
			// 方案2：使用新标签页（动态路由）展示产线详情时，修改对应菜单的meta.title，并重新生成路由
			// const find = findInTreeArray(userStore.dynamicMenus, menuVo => menuVo.name === `ProductionLineDetail_${request.productionId}`)
			// if (!find) {
			// 	throw Error(`无法找到名称为【ProductionLineDetail_${request.productionId}】的菜单`)
			// }
			// find.meta.title = request.productionName
			// userStore.generateMenu()
			// generateRoutes()
			// // 修改标签页的标题
			// for (const menuVo of navTabsStore.openedTabs) {
			// 	if (menuVo.name === `ProductionLineDetail_${request.productionId}`) {
			// 		menuVo.meta.title = request.productionName
			// 		break
			// 	}
			// }
		}
	})
}

const tableMaxHeight = ref<number>(800)
const dialogVisible = reactive({
	item: false,
	building: false
})
const tabActiveName = ref<string>('collection')
const productionLineDataList = ref<ProductionLineDataForTab[]>([])
const itemIdDisplayed = ref<number>()
const params = reactive<{
	userId_eq?: number,
	productionName_like?: string,
	itemId_eq?: number
	type_eq?: number
}>({
	userId_eq: undefined,
	productionName_like: undefined,
	itemId_eq: undefined,
	type_eq: 1
})
const userOptionList = ref<SysUser[]>([])
const itemOptionList = ref<GItem[]>([])
const tableLoading = ref(false)
const tableData = ref<ProductionCollectionVo[]>([])

// 计算表格最大高度
const getTableMaxHeight: DebouncedFunc<() => typeof getTableMaxHeight> = debounce(() => {
	tableMaxHeight.value = calcMaxHeightWithExtra(63, '#userProduction-form-title', '#userProduction-form', '#userProduction-table-title', '#userProduction-pagination')
	return getTableMaxHeight
}, 100, {
	leading: true,
	trailing: false,
	maxWait: 100
})

const removeTab = (name: TabPaneName) => {
	const index = productionLineDataList.value.findIndex(item => item.name === name)
	remove(productionLineDataList.value, item => item.name === name)
	if (tabActiveName.value === name) {
		tabActiveName.value = productionLineDataList.value[index - 1]?.name ?? 'collection'
	}
}

const showLineDetail = async (row: ProductionCollectionVo) => {
	// 方案1：使用el-tabs展示产线详情
	tableLoading.value = true
	try {
		const tabName = `ProductionLineDetail_${row.id}`
		if (!productionLineDataList.value.some(item => item.name === tabName)) {
			const userProduction = (await getUserProductionByIdApi(row.id)).data
			const parse = JSON.parse(userProduction.data!)
			productionLineDataList.value.push({
				treeData: parse.treeData,
				statistics: parse.statistics,
				name: tabName,
				label: row.productionName
			})
		}
		tabActiveName.value = tabName
	} finally {
		tableLoading.value = false
	}
	// 方案2：使用新标签页（动态路由）展示产线详情
	// const routeRecordName = `ProductionLineDetail_${row.id}`
	// const parentMenu = findInTreeArray(userStore.dynamicMenus, menuVo => menuVo.name === 'GameTool')
	// if (!parentMenu) {
	// 	throw Error('无法找到名称为【GameTool】的菜单')
	// }
	// if (!findInTreeArray(parentMenu.children, menuVo => menuVo.name === routeRecordName)) {
	// 	parentMenu.children.push({
	// 		name: routeRecordName,
	// 		path: `productionLineDetail/${row.id}`,
	// 		meta: {
	// 			type: 1,
	// 			fullPath: `/gameTool/productionLineDetail/${row.id}`,
	// 			title: row.productionName,
	// 			icon: 'local-cus-ruleEngine',
	// 			keepAlive: true,
	// 			affix: false,
	// 			hidden: true,
	// 			sort: Constants.MAX_INTEGER
	// 		},
	// 		children: [],
	// 		component: '/src/components/production-line-detail.vue'
	// 	})
	// 	userStore.generateMenu()
	// 	generateRoutes()
	// }
	// await routePush({name: routeRecordName})
}

const showItemDetail = (itemId: number) => {
	itemIdDisplayed.value = itemId
	dialogVisible.item = true
}

const handleSearch: DebouncedFunc<() => void> = debounce(() => {
	if (isVisitor()) {
		messageWarning('游客模式下，产线收藏功能不可用，请注册账号后使用~')
	} else {
		pageRef.value!.reload()
	}
}, 200, {
	leading: true,
	trailing: false,
	maxWait: 200
})

const resetParams = () => {
	if (isAdmin()) {
		params.userId_eq = undefined
	}
	params.productionName_like = undefined
	params.itemId_eq = undefined
}

const resetSearch = () => {
	resetParams()
	handleSearch()
}

if (!isVisitor()) {
	getAllItemApi().then(response => {
		itemOptionList.value = response.data
	})
}

if (isAdmin()) {
	getAllUserApi().then(response => {
		userOptionList.value = response.data
	})
} else {
	params.userId_eq = userStore.userId
}

const checkRouteParams = () => {
	const routeParams = routeParamsStore.getParams()
	if (routeParams?.handleSearch === 1) {
		handleSearch()
	}
	routeParamsStore.removeParams()
}

onMounted(() => {
	useEventListener(window, 'resize', getTableMaxHeight()!)
	handleSearch()
})

// 该页面开启缓存且首次或后续进入时执行，刷新页面不执行
onActivated(() => {
	useEventListener(window, 'resize', getTableMaxHeight()!)
	checkRouteParams()
})

onBeforeRouteLeave(() => {
	window.removeEventListener('resize', getTableMaxHeight)
})

</script>

<style lang="scss" scoped>
.line-list-tab-pane {
	padding: 0 var(--cus-box-shadow-width);
	animation: fade-in 0.5s;
}

.line-detail-tab-pane {
	padding: var(--cus-box-shadow-width);
	animation: fade-in 0.5s;
}

.custom-tree-node {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: var(--el-font-size-base);
	padding-right: 8px;
}
</style>
